<template>
  <div class="page-container">
    <el-card class="page-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon size="20" class="header-icon"><User /></el-icon>
            <h3>用户管理</h3>
            <span class="header-desc">管理系统用户和角色分配</span>
          </div>
          <div class="header-right">
            <el-button type="primary" @click="showAddUser" :icon="Plus" plain>
              新增用户
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form :model="searchForm" inline>
          <el-form-item label="用户名">
            <el-input 
              v-model="searchForm.username" 
              placeholder="请输入用户名" 
              clearable
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item label="昵称">
            <el-input 
              v-model="searchForm.nickname" 
              placeholder="请输入昵称" 
              clearable
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px;">
              <el-option label="启用" value="0" />
              <el-option label="禁用" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="loadUsers" :icon="Search">搜索</el-button>
            <el-button @click="resetSearch" :icon="Refresh">重置</el-button>
            <el-button @click="refreshRoles" type="success" :icon="Setting">刷新角色</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table :data="users" style="width:100%;" class="user-table"
                v-loading="loading"
                element-loading-text="正在加载..."
                element-loading-background="rgba(255, 255, 255, 0.6)">
        <el-table-column prop="username" label="用户名" min-width="120">
          <template #default="scope">
            <div class="user-name-cell">
              <el-avatar :size="32" :src="scope.row.avatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              <span class="username">{{ scope.row.username }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="nickname" label="昵称" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
        <el-table-column prop="phone" label="手机号" min-width="120" />
        <el-table-column label="角色" min-width="150">
          <template #default="scope">
            <el-tag 
              v-for="role in getUserRoles(scope.row.id)" 
              :key="role.roleId" 
              type="primary" 
              size="small"
              class="role-tag"
            >
              {{ role.roleName }}
            </el-tag>
            <el-tag v-if="!getUserRoles(scope.row.id).length" type="info" size="small">
              暂无角色
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch 
              v-model="scope.row.status" 
              active-value="0" 
              inactive-value="1"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="editUser(scope.row)" :icon="Edit">
              编辑
            </el-button>
            <el-button size="small" type="warning" @click="assignRole(scope.row)" :icon="Setting">
              分配角色
            </el-button>
            <el-button size="small" type="danger" @click="deleteUser(scope.row)" :icon="Delete">
              删除
            </el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无用户数据" />
        </template>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadUsers"
          @current-change="loadUsers"
        />
      </div>
    </el-card>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog 
      v-model="showAdd" 
      :title="form.id ? '编辑用户' : '新增用户'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" placeholder="请输入用户名" :disabled="!!form.id" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="form.nickname" placeholder="请输入昵称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="!form.id">
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="form.confirmPassword" type="password" placeholder="请确认密码" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio value="0">启用</el-radio>
            <el-radio value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAdd=false">取消</el-button>
          <el-button type="primary" @click="saveUser" :loading="saving">
            {{ saving ? '保存中...' : '保存' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog v-model="showRole" title="分配角色" width="500px" :close-on-click-modal="false">
      <div class="role-dialog-content">
        <div class="user-info">
          <el-avatar :size="40" :src="currentUser?.avatar">
            <el-icon><User /></el-icon>
          </el-avatar>
          <div class="user-details">
            <div class="user-name">{{ currentUser?.username }}</div>
            <div class="user-nickname">{{ currentUser?.nickname }}</div>
          </div>
        </div>
        
        <div class="role-selection">
          <el-checkbox-group v-model="checkedRoles">
            <div class="role-grid">
              <el-checkbox 
                v-for="role in allRoles" 
                :key="role.roleId" 
                :value="role.roleId"
                class="role-checkbox"
              >
                <div class="role-item">
                  <div class="role-name">{{ role.roleName }}</div>
                  <div class="role-key">{{ role.roleKey }}</div>
                </div>
              </el-checkbox>
            </div>
          </el-checkbox-group>
        </div>
        
        <!-- API不可用时的提示 -->
        <el-alert 
          v-if="!roleApiAvailable" 
          title="提示" 
          type="info" 
          :closable="false"
          style="margin-top: 16px;"
        >
          <template #default>
            当前为演示模式，角色分配操作将在后端接口完成后生效
          </template>
        </el-alert>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showRole=false">取消</el-button>
          <el-button type="primary" @click="saveRoles" :loading="roleSaving">
            {{ roleSaving ? '保存中...' : (roleApiAvailable ? '保存角色' : '保存设置') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, Plus, Search, Refresh, Edit, Delete, Setting
} from '@element-plus/icons-vue'

const users = ref([])
const showAdd = ref(false)
const form = ref({})
const formRef = ref()
const saving = ref(false)
const loading = ref(false)

// 角色相关
const showRole = ref(false)
const allRoles = ref([])
const checkedRoles = ref([])
const currentUser = ref(null)
const roleSaving = ref(false)
const userRoles = ref({}) // 存储用户角色映射
const roleApiAvailable = ref(true) // 角色API是否可用
const localRoleData = ref({}) // 本地模拟的角色数据

// 搜索表单
const searchForm = ref({
  username: '',
  nickname: '',
  status: ''
})

// 分页
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 表单验证规则
const formRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== form.value.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
}

// 获取用户角色
const getUserRoles = (userId) => {
  // 如果API可用，返回真实数据
  if (roleApiAvailable.value) {
    return userRoles.value[userId] || []
  }
  // 如果API不可用，返回本地模拟数据
  return localRoleData.value[userId] || []
}

const loadUsers = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
      ...searchForm.value
    }
    // 修复API路径
    const res = await request.get('/user/list', { params })
    if (res.code === 200) {
      const payload = res.data ?? res
      const data = payload?.data ?? payload
      const records = data?.records ?? data?.list ?? data
      const total = data?.total ?? 0
      users.value = Array.isArray(records) ? records : (records?.records ?? [])
      pagination.value.total = total
      // 加载用户角色
      await loadUserRoles()
    }
  } catch (error) {
    console.error('加载用户失败:', error)
    ElMessage.error('加载用户失败')
  } finally {
    loading.value = false
  }
}

const loadUserRoles = async () => {
  console.log('=== 开始加载用户角色 ===')
  console.log('roleApiAvailable:', roleApiAvailable.value)
  console.log('localRoleData:', localRoleData.value)
  
  // 如果已知角色API不可用，使用本地数据
  if (!roleApiAvailable.value) {
    console.log('使用本地角色数据模式')
    users.value.forEach(user => {
      userRoles.value[user.id] = localRoleData.value[user.id] || []
      console.log(`用户 ${user.id} 的角色:`, userRoles.value[user.id])
    })
    return
  }

  try {
    for (const user of users.value) {
      try {
        const res = await request.get(`/user/${user.id}/roles`)
        if (res.code === 200) {
          userRoles.value[user.id] = (res.data ?? res) || []
          console.log(`✅ 从API加载用户 ${user.id} 的角色:`, userRoles.value[user.id])
        }
      } catch (error) {
        // 如果是500错误，说明后端接口未实现，标记API不可用并切换到本地数据
        if (error.response?.status === 500) {
          roleApiAvailable.value = false
          console.warn('❌ 用户角色API暂不可用，切换到本地模拟模式')
          // 使用本地模拟数据
          users.value.forEach(u => {
            userRoles.value[u.id] = localRoleData.value[u.id] || []
            console.log(`🔄 本地数据 - 用户 ${u.id} 的角色:`, userRoles.value[u.id])
          })
          return
        } else {
          console.error(`❌ 加载用户${user.id}角色失败:`, error)
          userRoles.value[user.id] = []
        }
      }
    }
  } catch (error) {
    console.error('❌ 加载用户角色失败:', error)
  }
  
  console.log('=== 用户角色加载完成 ===')
  console.log('最终 userRoles:', userRoles.value)
}

const resetSearch = () => {
  searchForm.value = { username: '', nickname: '', status: '' }
  pagination.value.pageNum = 1
  loadUsers()
}

// 刷新角色数据
const refreshRoles = async () => {
  ElMessage.info('正在刷新角色数据...')
  
  // 重新加载本地数据
  const savedRoleData = localStorage.getItem('mockUserRoles')
  if (savedRoleData) {
    try {
      localRoleData.value = JSON.parse(savedRoleData)
      console.log('✅ 重新加载本地角色数据:', localRoleData.value)
    } catch (e) {
      console.error('解析本地角色数据失败:', e)
    }
  }
  
  // 强制重新加载用户角色
  await loadUserRoles()
  
  ElMessage.success('角色数据刷新完成')
  console.log('🔄 角色数据已强制刷新')
}

const showAddUser = () => {
  form.value = { status: '0' }
  showAdd.value = true
}

const saveUser = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
  } catch {
    return
  }
  
  saving.value = true
  
  try {
    const { confirmPassword, ...submitData } = form.value
    
    if (form.value.id) {
      // 修复API路径
      await request.put('/user', submitData)
      ElMessage.success('修改成功')
    } else {
      // 修复API路径
      await request.post('/user', submitData)
      ElMessage.success('添加成功')
    }
    showAdd.value = false
    loadUsers()
  } catch (error) {
    console.error('保存用户失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

const editUser = (row) => {
  form.value = { ...row }
  showAdd.value = true
}

const deleteUser = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除用户"${row.username}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 修复API路径
    await request.delete(`/user/${row.id}`)
    ElMessage.success('删除成功')
    loadUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleStatusChange = async (row) => {
  try {
    await request.put('/user', { ...row })
    // ElMessage.success('状态更新成功') // 移除弹窗提示
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('状态更新失败')
    // 恢复原状态
    row.status = row.status === '0' ? '1' : '0'
  }
}

const assignRole = async (row) => {
  currentUser.value = row
  
  try {
    // 加载所有角色
    const res1 = await request.get('/role/list')
    if (res1.code === 200) {
      const payload = res1.data ?? res1
      const data = payload?.data ?? payload
      allRoles.value = data?.records || data || []
    }
    
    // 加载用户已有角色
    try {
      const res2 = await request.get(`/user/${row.id}/roles`)
      if (res2.code === 200) {
        const payload2 = res2.data ?? res2
        checkedRoles.value = (payload2 || []).map(r => r.roleId)
      }
    } catch (error) {
      // 如果是500错误，说明后端接口未实现，使用本地模拟数据
      if (error.response?.status === 500) {
        roleApiAvailable.value = false
        // 从本地模拟数据中获取用户角色
        const localRoles = localRoleData.value[row.id] || []
        checkedRoles.value = localRoles.map(r => r.roleId)
        console.warn('用户角色接口未实现，使用本地模拟数据')
      } else {
        throw error
      }
    }
    
    showRole.value = true
  } catch (error) {
    console.error('加载角色数据失败:', error)
    ElMessage.error('加载角色数据失败')
  }
}

const saveRoles = async () => {
  roleSaving.value = true
  
  try {
    // 修复API路径
    await request.put(`/user/${currentUser.value.id}/roles`, checkedRoles.value)
    ElMessage.success('角色分配成功')
    showRole.value = false
    
    // 🔧 直接更新角色显示，而不是重新加载所有用户数据
    const selectedRoles = allRoles.value.filter(role => 
      checkedRoles.value.includes(role.roleId)
    )
    userRoles.value[currentUser.value.id] = selectedRoles
    
    console.log('✅ 角色分配成功，界面已更新:', {
      userId: currentUser.value.id,
      roles: selectedRoles
    })
  } catch (error) {
    console.error('保存角色失败:', error)
    if (error.response?.status === 500) {
      // 后端接口未实现时，模拟成功操作，关闭对话框
      ElMessage.info('角色分配操作已记录，后端接口开发完成后将生效')
      showRole.value = false
      
      // 更新本地模拟数据
      const selectedRoles = allRoles.value.filter(role => 
        checkedRoles.value.includes(role.roleId)
      )
      localRoleData.value[currentUser.value.id] = selectedRoles
      
      // 🔧 重要：同步更新界面显示的用户角色
      userRoles.value[currentUser.value.id] = selectedRoles
      
      // 保存到localStorage
      localStorage.setItem('mockUserRoles', JSON.stringify(localRoleData.value))
      
      console.log('✅ 角色分配完成，界面已更新:', {
        userId: currentUser.value.id,
        roles: selectedRoles,
        userRoles: userRoles.value[currentUser.value.id]
      })
      
      // 发送权限更新事件，通知其他组件刷新权限
      window.dispatchEvent(new CustomEvent('permissionsUpdated', {
        detail: { userId: currentUser.value.id, roles: checkedRoles.value }
      }))
    } else {
      ElMessage.error('保存角色失败')
    }
  } finally {
    roleSaving.value = false
  }
}

onMounted(() => {
  console.log('=== 用户管理页面初始化 ===')
  
  // 加载本地模拟的角色数据
  const savedRoleData = localStorage.getItem('mockUserRoles')
  if (savedRoleData) {
    try {
      localRoleData.value = JSON.parse(savedRoleData)
      console.log('✅ 加载本地角色数据:', localRoleData.value)
    } catch (e) {
      console.error('解析本地角色数据失败:', e)
    }
  } else {
    console.log('⚠️ 没有本地角色数据')
  }
  
  loadUsers()
})
</script>

<style scoped>
.page-container {
  padding: 0;
}

.page-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  color: #409eff;
}

.card-header h3 {
  margin: 0;
  color: #2c3e50;
  font-weight: 600;
}

.header-desc {
  color: #909399;
  font-size: 14px;
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.user-table {
  margin-bottom: 20px;
}

.user-name-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}

.username {
  font-weight: 500;
  color: #2c3e50;
}

.role-tag {
  margin-right: 4px;
  margin-bottom: 4px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

.role-dialog-content {
  max-height: 500px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.user-details {
  flex: 1;
}

.user-name {
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 4px;
}

.user-nickname {
  color: #606266;
  font-size: 14px;
}

.role-selection {
  max-height: 300px;
  overflow-y: auto;
}

.role-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.role-checkbox {
  margin: 0;
  width: 100%;
}

.role-item {
  display: flex;
  flex-direction: column;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  transition: all 0.3s;
}

.role-item:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.role-name {
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 4px;
}

.role-key {
  font-size: 12px;
  color: #909399;
}

:deep(.el-table__row) {
  transition: background-color 0.3s;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.el-button--small) {
  margin-left: 8px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-checkbox__input.is-checked + .el-checkbox__label .role-item) {
  border-color: #409eff;
  background-color: #f0f9ff;
}
</style>